import 'dart:async';

import 'package:flutter/material.dart';

import '../../flutter_base_framework.dart';
import 'package:flutter_common_utils/flutter_common_utils.dart';

//  监听页面动画完成
Future<void> onPageAnimComplete() {
  final completeFuture = Completer<void>();
  postFrame((it) {
    final router = routeRecord.history.lastOrNull;
    if (router != null && router is ModalRoute) {
      final animation = router.animation;
      if (animation != null) {
        // 立即检查一次状态，防止动画已经完成
        if (animation.status == AnimationStatus.completed) {
          completeFuture.complete();
        } else {
          //将 listener 定义为具名函数而非变量，利用 Dart 的 函数声明提升（function hoisting） 特性，允许在函数内部引用自身
          void listener(AnimationStatus status) {
            if (status == AnimationStatus.completed) {
              completeFuture.complete();
              animation.removeStatusListener(listener);
            }
          }
          animation.addStatusListener(listener);
        }
      } else {
        completeFuture.complete();
      }
    } else {
      completeFuture.complete();
    }
  });
  return completeFuture.future;
}
